<?php

namespace Contact;

use Application\AdminAbstract;

class AdminController extends AdminAbstract
{
    protected $model;

    public function __construct()
    {
        parent::__construct();
        $this->model = new Model();
    }

    protected function getConfig()
    {
        return include(__DIR__ . '/config/module.config.php');
    }

    public function messageAction()
    {
        $form = $this->getForm(__NAMESPACE__ . '\Search');
        $multiCheckbox = $form->getElement('serviceId');
        $list = $this->model->getServiceList();
        array_unshift($list, 'All');
        $multiCheckbox->setOptions(['multiOptions' => $list]);
        if ($this->request->isGet() && $form->isValid($this->request->getQuery()->toArray())) {
            $search = $form->getValues();
            $allowed = ['submitted', 'firstName', 'lastName', 'phone'];
            $order = $this->request->getQuery('order');
            $desc = $this->request->getQuery('desc');
            if (false === array_search($order, $allowed)) {
                $order = $allowed[0];
                $desc = true;
            }
            if (null === $desc) {
                $result['desc'] = '&desc';
            } else {
                $desc = true;
            }
            if ($search['q']) {
                $result['messages'] = $this->model->search($search, $order, $desc);
            } else {
                $result['messages'] = $this->model->getList($order, $desc);
            }
        }
        $result['query'] = 'q=' . $this->request->getQuery('q') . '&serviceId=' .  $this->request->getQuery('serviceId');
        $result['search'] = $form;
        return $result;
    }

    public function deleteAction()
    {
        if ($id = $this->routeMatch->getParam('id')) {
            $this->model->delete($id);
        } else {
            if ($this->request->isPost()) {
                $id = explode(',', $this->request->getPost()->toArray()['checkboxId']);
                $this->model->delete($id);
            }
        }
        $this->redirect('admin/contact');
    }

    public function showAction()
    {
        if ($id = $this->routeMatch->getParam('id')) {
            $message = $this->model->find(compact('id'));
            if ($message) {
                $message['title'] = $this->model->getService($id);
                return compact('message');
            }
            $result['message'] = 'No such message';
        } else {
            $result['message'] = 'No ID';
        }
        return $result;
    }
}